//
//  QXQRCodeVC.swift
//  QXWeibo
//
//  Created by QinXin on 15/6/29.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import AVFoundation
import SVProgressHUD

class QXQRCodeVC: UIViewController, UITabBarDelegate, AVCaptureMetadataOutputObjectsDelegate {
    
    @IBOutlet weak var qrCodeLabel: UILabel!
    @IBOutlet weak var tabBar: UITabBar!
    @IBOutlet weak var scanLineProgressCons: NSLayoutConstraint!
    
    @IBOutlet weak var scannerHeightCons: NSLayoutConstraint!
    class func create() -> UINavigationController {
        let storyboard = UIStoryboard(name: "QXQRCodeVC", bundle: nil)
        return storyboard.instantiateInitialViewController() as! UINavigationController
    }
    
    @IBAction func close(sender: UIBarButtonItem) {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.selectedItem = tabBar.items![0];
        tabBar.delegate = self
        
        // ①
        setupSession()
        // ②
        setupLayers()
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        scanLineProgressCons.constant = 0.0;
        
        // ③
        startScan()

        UIView.animateWithDuration(2.0) { () -> Void in
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLineProgressCons.constant = 400.0;
            self.view.layoutIfNeeded()
        }
        
    }
    
    func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {

        if item.tag == 0 {
            
            scannerHeightCons.constant = 220.0;
            
        } else {
            
            scannerHeightCons.constant = 120.0;
        }
        
    }
    
    
    // MARK: - 二维码扫描相关
    
    // 二维码扫描会话
    lazy var qrCodeScanSession: AVCaptureSession = AVCaptureSession()
    // 扫描图像显示
    lazy var cameraLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.qrCodeScanSession)
    // 用于描绘图像中二维码的位置
    lazy var pickQRCodeLayer: CALayer = CALayer()
    // 输入设备
    lazy var inputDevice: AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
        do {
            return try AVCaptureDeviceInput(device: device)
        } catch {
            print(error)
            return nil
        }
    }()
    // 输出数据
    lazy var outputData: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    // 设置二维码视图
    func setupLayers () {
        
        pickQRCodeLayer.frame = view.bounds
        view.layer.insertSublayer(pickQRCodeLayer, atIndex: 0)
        
        cameraLayer.frame = view.bounds
        cameraLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
        view.layer.insertSublayer(cameraLayer, atIndex: 0)
    }
    
    // 清空视图（刷新,防止重复绘制）
    private func clearDrawLayer() {
        if pickQRCodeLayer.sublayers == nil {
            return
        }
        for subLayer in pickQRCodeLayer.sublayers! {
            subLayer.removeFromSuperlayer()
        }
    }
    
    // 根据四个点绘制四边形的函数
    private func drawCorners(codeObject: AVMetadataMachineReadableCodeObject) {
        print(codeObject)
        
        // 可以做动画绘图的，专门在图层中画图
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.greenColor().CGColor
        layer.fillColor = UIColor.clearColor().CGColor
        
        
        let path = UIBezierPath()
        
        // 定义 Point UnsafeMutablePointer -> var
        var point = CGPoint()
        var index = 0
        // 拿到第 0 个点
        CGPointMakeWithDictionaryRepresentation(codeObject.corners[index++] as! CFDictionary, &point)
        // 移动到第 0 个点
        path.moveToPoint(point)
        
        // 遍历剩余的点
        while index < codeObject.corners.count {
            CGPointMakeWithDictionaryRepresentation(codeObject.corners[index++] as! CFDictionary, &point)
            // 添加路线
            path.addLineToPoint(point)
        } 
        // 关闭路径
        path.closePath()
        
        layer.path = path.CGPath
        
        pickQRCodeLayer.addSublayer(layer)
    }
    
    // 开始扫描
    func startScan() {
        qrCodeScanSession.startRunning()
    }
    
    // 设置会话
    private func setupSession() {
        // 1. 判断能否添加输入设备
        if !qrCodeScanSession.canAddInput(inputDevice) {
            SVProgressHUD.showInfoWithStatus("您的摄像头有问题")
            return
        }
        
        // 2. 判断能否添加输出数据
        if !qrCodeScanSession.canAddOutput(outputData) {
            print("无法添加输出数据")
            return
        }
        
        // 3. 数据地址与设备进行连接
        qrCodeScanSession.addInput(inputDevice)
        qrCodeScanSession.addOutput(outputData)
        
        // 4. 设置检测数据类型，检测所有支持的数据格式
        outputData.metadataObjectTypes = outputData.availableMetadataObjectTypes
        
        // 5. 设置数据的代理
        outputData.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    }
    
    // MARK: - AVCaptureMetadataOutputObjectsDelegate
    func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
        
        // 清空图层
        clearDrawLayer()
        
        for object in metadataObjects {
            // 判断识别对象类型
            if object is AVMetadataMachineReadableCodeObject {
                // 转换数据类型
                let codeObject = cameraLayer.transformedMetadataObjectForMetadataObject(object as! AVMetadataObject) as! AVMetadataMachineReadableCodeObject
                
                drawCorners(codeObject)
                qrCodeLabel.text = codeObject.stringValue
            }
        }
    }
    

}
